﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Net;
using System.IO;
using System.Xml.Xsl;
using System.Xml.XPath;
using Elmah;
using System.Xml.Linq;
using System.Configuration;

namespace Core.Utils
{
    public class GmailClient
    {
        private string GmailUri { get; set; }
        private string UserName { get; set; }
        private string Password { get; set; }
        private List<GmailItem> newMailList;

        public GmailClient(string userName, string password)
        {
            GmailUri = ConfigurationManager.AppSettings["GmailFeed"];
            UserName = userName;
            Password = password;
        }
        /// <summary>
        /// I'd prefer to return the generic list here instead of using the GetMailItem 
        /// method to get individual items, but javascript doesn't play nice with generics.
        /// </summary>
        /// 
        public List<GmailItem> GetUnreadMail()
        {
            try
            {
                // Get the XML feed from mail.google.com
                // Create a web request to get the xml feed
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GmailUri);
                request.Method = "GET";
                request.Credentials = new NetworkCredential(UserName, Password);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // If the request/response is successful
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(response.GetResponseStream());

                    XmlNodeList lEntries = doc.DocumentElement.GetElementsByTagName("entry");
                    var itemList = new List<GmailItem>();

                    for (int i = 0; i < lEntries.Count; i++)
                    {
                        var itm = new GmailItem();
                        itm.Title = (lEntries[i]["title"] != null) ? lEntries[i]["title"].InnerText : string.Empty;
                        itm.Link = (lEntries[i]["link"] != null) ? lEntries[i]["link"].Attributes["href"].Value : string.Empty;
                        itm.Summary = (lEntries[i]["summary"] != null) ? lEntries[i]["summary"].InnerText : string.Empty;
                        itm.PubDate = DateTime.Parse(lEntries[i]["issued"].InnerText, System.Globalization.CultureInfo.InvariantCulture);
                        itm.ID = (lEntries[i]["id"] != null) ? lEntries[i]["id"].InnerText : string.Empty;
                        itm.AuthorEmail = (lEntries[i]["author"] != null && lEntries[i]["author"]["email"] != null) ? lEntries[i]["author"]["email"].InnerText : string.Empty;
                        itm.AuthorName = (lEntries[i]["author"] != null && lEntries[i]["author"]["name"] != null) ? lEntries[i]["author"]["name"].InnerText : string.Empty;

                        itemList.Add(itm);
                    }

                    newMailList = itemList;

                    return itemList;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }

            return null;
        }


        /// <summary>
        /// The number of items in the unread mail collection
        /// </summary>
        public int UnreadMailCount
        {
            get
            {
                if (newMailList != null)
                {
                    return newMailList.Count;
                }
                else
                {
                    return 0;
                }
            }
        }
        /// <summary>
        /// Returns the GmailItem at the specified index
        /// </summary>
        /// <param name="index">Index if the mail item to return</param>
        public GmailItem GetMailItem(int index)
        {
            if (newMailList == null || index < 0 || index > newMailList.Count)
            {
                throw new IndexOutOfRangeException();
            }

            return newMailList[index];
        }
    }
}
